package demo1;

public class MyQueue {
    static class Node{
        public int val;
        public Node next;

        public Node(int val) {
            this.val = val;
        }
    }
    public Node head; //单链表头部
    public Node last; //单链表尾部

    //入队列
    public boolean offer(int val) {
        Node newNode  = new Node(val);
        if (isEmpty()) {
            this.head = newNode;
            this.last = newNode;
            return true;
        }
        this.last.next = newNode;
        this.last = newNode;
        return true;
    }

    //出队列
    public int poll() {
        //如果队列为空的话  返回 -1
        if (isEmpty()) {
            return -1;
        }
        int val = this.head.val;
        //判断只有一个节点的情况下
        if (this.head == this.last) {
            this.last = null;
        }
        this.head = this.head.next;
        return val;
    }

    //获取队头元素
    public int peek() {
        //如果队列为空的话 返回一个 -1
        if (isEmpty()) {
            return -1;
        }
        return this.head.val;
    }

    //获取队列中有效元素个数
    public int size() {
        Node cur = this.head;
        int count = 0;
        while (cur != null) {
            count++;
            cur = cur.next;
        }
        return count;
    }
    //判断队列是否为空
    public boolean isEmpty() {
        return this.head == null;
    }
}
